package slowquery

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

// GormVLogger 慢查询日志
type GormVLogger struct {
	SlowThreshold time.Duration
	LogLevel      logger.LogLevel
	Colorful      bool
}

func NewGormVLogger() *GormVLogger {
	return &GormVLogger{
		SlowThreshold: 1 * time.Millisecond,
		LogLevel:      logger.Warn,
		Colorful:      true,
	}
}

func CreateLogFile() (*os.File, error) {
	LogFile := fmt.Sprintf("%s/slow_query.log", getProjectDir())
	logFile, err := os.OpenFile(LogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		fmt.Printf("error opening file: %v", err.Error())
		return nil, err
	}
	os.Stdout = logFile
	return logFile, nil
}

// InitConn 初始化连接
func InitConn() error {
	logFile, _ := CreateLogFile()
	dns := "homed:123456@tcp(82.156.87.105:3306)/fk_school?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dns), &gorm.Config{
		Logger: logger.New(
			log.New(logFile, "\r\n", log.LstdFlags),
			logger.Config{
				SlowThreshold: NewGormLogger().SlowThreshold,
				LogLevel:      NewGormLogger().LogLevel,
				Colorful:      NewGormLogger().Colorful,
			},
		),
	})
	if err != nil {
		fmt.Printf("error opening database connection: %v", err.Error())
		return err

	}
	var userList []User
	// 限制查询
	//err := GetConn().Limit(556).Offset(998).Find(&userList).Error
	err = db.Where("name LIKE ?", "%蔡%").Where("user_id=?", 2).Find(&userList).Error
	if err != nil {
		fmt.Println("查询失败!")
	}
	fmt.Println(":", userList)
	return nil
}
